import urllib2, re
import vkontakte.auth
from vkontakte.common import unescape

class GroupsFetcher:
    def __init__(self, vkontakte_auth):
        self._auth = vkontakte_auth
        self._groups_list = []
        self._accepted_groups_list = []        
        
    def fetch_list(self):
        opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self._auth.get_cookie()))
        response = opener.open('http://vkontakte.ru/groups.php')
        udata = unescape(unicode(response.read(), 'windows-1251'))
        self._groups_list = re.findall(r"groupName(\d+).+>(.+)</a>", udata)
        for (gid, name) in self._groups_list:
            if not re.search("processRequest\(%s" % gid, udata):
                self._accepted_groups_list += [(gid, name)]
        
    def GetGroups(self):
        if len(self._groups_list) == 0:
            self.fetch_list()
        
        return self._groups_list
    
    def GetAcceptedGroups(self):
        if len(self._accepted_groups_list) == 0:
            self.fetch_list()
            
        return self._accepted_groups_list
    